package com.haorui.lygyd.wxapi.utils;

import com.haorui.base.system.entity.JiekouEntity;
import com.haorui.base.system.service.JiekouService;
import com.haorui.lygyd.wxapi.common.CommonUtil;
import lombok.Cleanup;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * @author 陈刚
 * @version 1.0
 * @project znsm
 * @package com.haorui.znsm.wxapi.utils
 * @createDate 2018-03-22 18:34
 * @modfiyDate
 * @function
 */
@Component
public class WXUserQRCode {
    @Value("${spring.resources.static-locations}")
    private  String fileSavePath;
    @Autowired
    private JiekouService jiekouService;
    public static final String wxMemberQRcode="qrcode";
    public String getMemberQRcode(String memberKaHao) throws IOException {
        String savePath=fileSavePath.replace("file:","");
        savePath+= File.separator+wxMemberQRcode;
        File desDir=new File(savePath);
        if(!desDir.exists()){
            desDir.mkdirs();
        }

        File desPhoto=new File(desDir,memberKaHao+".jpg");
        if(!desPhoto.exists()){
            JiekouEntity jiekouEntity=jiekouService.findOne("1");
            String appid=jiekouEntity.getXiaochengxuAppID();
            String appsecret=jiekouEntity.getXiaochengxuSecret();
//            String appid="wxdb14f1dbb833e462";
//            String appsecret="148950763214895076321489507632zn";
            byte[] b= CommonUtil.getUserQRCode(appid,appsecret,memberKaHao);
            @Cleanup FileOutputStream fout=new FileOutputStream(desPhoto);
            IOUtils.write(b,fout);

            return desPhoto.getName();
        }
        return desPhoto.getName();
    }
    public String getMemberQRcode(String memberKaHao,String goodsId) throws IOException {
        String savePath=fileSavePath.replace("file:","");
        savePath+= File.separator+wxMemberQRcode;
        File desDir=new File(savePath);
        if(!desDir.exists()){
            desDir.mkdirs();
        }

        File desPhoto=new File(desDir,memberKaHao+"_"+goodsId+".jpg");
        if(!desPhoto.exists()){
            JiekouEntity jiekouEntity=jiekouService.findOne("1");
            String appid=jiekouEntity.getXiaochengxuAppID();
            String appsecret=jiekouEntity.getXiaochengxuSecret();
            byte[] b=CommonUtil.getUserQRCodelb(appid,appsecret,memberKaHao,goodsId);
            @Cleanup FileOutputStream fout=new FileOutputStream(desPhoto);
            IOUtils.write(b,fout);

            return desPhoto.getName();
        }
        return desPhoto.getName();
    }
}
